package cn.iocoder.yudao.module.book.service.minio;

import cn.iocoder.yudao.module.book.config.MinioConfig;
import io.minio.GetPresignedObjectUrlArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.http.Method;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.InputStream;

@Service
public class MinioService {
    @Resource
    private MinioClient minioClient;
    @Resource
    private MinioConfig minioConfig;
    
    // 生成预签名上传URL
    public String getPresignedUploadUrl(String objectName) throws Exception {
        return minioClient.getPresignedObjectUrl(
            GetPresignedObjectUrlArgs.builder()
                .method(Method.PUT)
                .bucket(minioConfig.getBucketName())
                .object(objectName)
                .expiry(60 * 60) // 1小时有效期
                .build());
    }
    
    // 上传文件
    public void uploadFile(String objectName, InputStream stream, long size, String contentType) throws Exception {
        minioClient.putObject(
            PutObjectArgs.builder()
                .bucket(minioConfig.getBucketName())
                .object(objectName)
                .stream(stream, size, -1)
                .contentType(contentType)
                .build());
    }

    public String getFileUrl(String objectName) {
        return minioConfig.getEndpoint() + "/" + minioConfig.getBucketName() + "/" + objectName;
    }
}